package com.ec.au.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ec.au.constant.SysConstant;
import com.ec.au.utils.DateUtil;
import com.ec.common.domain.Result;
import com.ec.au.domain.dto.UserRegisterFormDTO;
import com.ec.au.domain.po.PageBean;
import com.ec.au.domain.po.Role;
import com.ec.au.domain.po.User;
import com.ec.au.service.RoleService;
import com.ec.au.service.UserService;
import com.github.pagehelper.util.StringUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.time.LocalDateTime;
import java.util.*;

@RestController
@RequestMapping("/system")
public class SystemController {
    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;

    BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();

    @Value("${avatarImagesFilePath}")
    private String avatarImagesFilePath;

    @PostMapping("/checkUserName")
    @PreAuthorize("hasAuthority('system:user')")
    public Result checkUserName(@RequestBody User user){
        if(userService.getByUserName(user.getUserName())==null){
            return Result.ok();
        }else{
            return Result.error("用户名已存在");
        }
    }

    @GetMapping("/users")
    @PreAuthorize("hasAuthority('system:user')")
    public Result<Map<String, Object>> getUsers(Integer pageNum, Integer pageSize,String query) {
        Page<User> pageResult = userService.page(new Page<>(pageNum,pageSize), new QueryWrapper<User>().like(StringUtil.isNotEmpty(query), "user_name", query).eq("is_deleted",0));
        List<User> userList = pageResult.getRecords();
        for(User user:userList){
            // 获取角色
            Role role = roleService.getById(user.getRoleId());
            // 设置角色
            user.setRole(role);
        }
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("userList",userList);
        resultMap.put("total",pageResult.getTotal());
        return Result.ok(resultMap);
    }


    @PostMapping("/user/delete")
    @PreAuthorize("hasAuthority('system:user')")
    public Result<Void> deleteUser(@RequestBody long[] ids) {
        if(userService.deleteUsersLogic(ids)){
            return Result.ok();
        }else{
            return Result.error("失败");
        }
    }

    @PostMapping("/user/save")
    @PreAuthorize("hasAuthority('system:user')")
    public Result<Void> editUser(@RequestBody User user) {
        if(user.getId()==null || user.getId()==-1){
            user.setCreateTime(LocalDateTime.now());
            user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
            userService.save(user);
        }else{
            user.setUpdateTime(LocalDateTime.now());
            userService.updateById(user);
        }
        return Result.ok();
    }

    @PostMapping("/updateStatus")
    @PreAuthorize("hasAuthority('system:user')")
    public Result<Void> updateStatus(@RequestBody User user) {
        User sysUser = userService.getById(user.getId());
        sysUser.setStatus(user.getStatus());
        userService.updateById(sysUser);
        return Result.ok();
    }

    @GetMapping("/user/{id}")
    @PreAuthorize("hasAuthority('system:user')")
    public Result findById(@PathVariable(value = "id")Integer id){
        User sysUser = userService.getById(id);
        Map<String,Object> map=new HashMap<>();
        map.put("sysUser",sysUser);
        return Result.ok(map);
    }

    @GetMapping("/resetPassword/{id}")
    @PreAuthorize("hasAuthority('system:user')")
    public Result resetPassword(@PathVariable(value = "id")Integer id){
        User sysUser = userService.getById(id);
        sysUser.setPassword(bCryptPasswordEncoder.encode(SysConstant.DEFAULT_PASSWORD));
        sysUser.setUpdateTime(LocalDateTime.now());
        userService.updateById(sysUser);
        return Result.ok();
    }
    @RequestMapping("/updateAvatar")
    @PreAuthorize("hasAuthority('system:user')")
    public Result updateAvatar(@RequestBody User user){
        User currentUser = userService.getById(user.getId());
        currentUser.setAvatar(user.getAvatar());
        userService.updateById(currentUser);
        return Result.ok();
    }

    /**
     * 上传用户头像图片
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping("/uploadImage")
    @PreAuthorize("hasAuthority('system:user')")
    public Map<String,Object> uploadImage(MultipartFile file)throws Exception{
        Map<String,Object> resultMap=new HashMap<>();
        if(!file.isEmpty()){
            // 获取文件名
            String originalFilename = file.getOriginalFilename();
            String suffixName=originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFileName= DateUtil.getCurrentDateStr()+suffixName;
            FileUtils.copyInputStreamToFile(file.getInputStream(),new File(avatarImagesFilePath+newFileName));
            resultMap.put("code",0);
            resultMap.put("msg","上传成功");
            Map<String,Object> dataMap=new HashMap<>();
            dataMap.put("title",newFileName);
            dataMap.put("src","image/userAvatar/"+newFileName);
            resultMap.put("data",dataMap);
        }
        return resultMap;
    }
}
